package com.ehuoyun.ecstore.biz;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.ehuoyun.ecstore.model.Advertisement;
import com.ehuoyun.ecstore.model.User;
import com.google.appengine.api.datastore.Blob;

@Component
@Transactional
public class AdvertisementMgr {
	@PersistenceContext(type=PersistenceContextType.EXTENDED)
    private EntityManager em;
	
	public List<Advertisement> getAllAdvertisements(User user) {
		List<Advertisement> ads;
		if(user == null) {
			ads = (List<Advertisement>)em.createQuery(
				"SELECT FROM com.ehuoyun.ecstore.model.Advertisement ad WHERE ad.createdBy > :userId")
				.setParameter("userId", 0)
				.getResultList();
		} else {
			ads = (List<Advertisement>)em.createQuery(
					"SELECT FROM com.ehuoyun.ecstore.model.Advertisement ad WHERE ad.createdBy = :userId")
					.setParameter("userId", user.getId())
					.getResultList();
		}
		return ads;
	}

	public Advertisement getAdvertisement(Long id) {
		Advertisement ad = (Advertisement)em.createQuery(
				"SELECT FROM com.ehuoyun.ecstore.model.Advertisement WHERE id=" + id)
				.getSingleResult();
		return ad;
	}

	public void save(Advertisement ad) {
		if(ad.getId() == null) {
			em.persist(ad);
		} else {
			Advertisement newAd = em.find(Advertisement.class, ad.getId());
			newAd.setLocation(ad.getLocation());
		    newAd.setCreatedDate(ad.getCreatedDate());
		    newAd.setCreatedBy(ad.getCreatedBy());
		    newAd.setName(ad.getName());
		    newAd.setOwner(ad.getOwner());
		    newAd.setWidth(ad.getWidth());
		    newAd.setHeight(ad.getHeight());
		    newAd.setPrice(ad.getPrice());
		    newAd.setCycle(ad.getCycle());
		    newAd.setCarTraffic(ad.getCarTraffic());
		    newAd.setManTraffic(ad.getManTraffic());
		    newAd.setAdClient(ad.getAdClient());
		    newAd.setAdType(ad.getAdType());
		    newAd.setAdMakingType(ad.getAdMakingType());
		    newAd.setAdLocationType(ad.getAdLocationType());
		    newAd.setImage(ad.getImage());
		    em.merge(newAd);
			em.flush();
		}
	}
	
	public Blob getAdImage(Long id) {
		if(id == null) {
			return null;
		}
		Advertisement ad = (Advertisement)em.createQuery(
				"SELECT FROM com.ehuoyun.ecstore.model.Advertisement WHERE id=" + id)
				.getSingleResult();
		return ad.getImage();
	}
}
